// 建立连接对象（还未发起连接）
var socket = new SockJS("http://localhost:8080/webSocketServer");

// 获取 STOMP 子协议的客户端对象
var stompClient = Stomp.over(socket);

// 向服务器发起websocket连接并发送CONNECT帧
stompClient.connect({}, function connectCallback(frame) {
	// 连接成功时（服务器响应 CONNECTED 帧）的回调方法
	setMessageInnerHTML("连接成功");

	var storage = window.localStorage;
	var Who = document.getElementById("who");
	var myname = storage.getItem("username");
	Who.innerHTML = "<option value=" + myname + "> " + myname + " 说:</option>";
	stompClient.subscribe('/user/'+myname +'/subscribeTest' , function(response) {
	
		var returnData = response.body;
		var Words = document.getElementById("words");
		var str = "";
		var TalkWords = document.getElementById("text");
		var msg = TalkWords.value;
		var myname = storage.getItem("username");
		str = '<div class="atalk"><span>' + returnData
				+ '</span></div>';
		// window.location.href="http://localhost:8080/first/index.html";
		Words.innerHTML = Words.innerHTML + str;

	});
}, function errorCallBack(error) {
	// 连接失败时（服务器响应 ERROR 帧）的回调方法
	setMessageInnerHTML("连接失败");
});

//发送消息
function send() {
	//1，获取text中的信息
	var text1 = document.getElementById('text').value;
	//2，页面信息（获取用户名）
	var storage = window.localStorage;
	var myname = storage.getItem("username");
	message = myname + "说: " + text1;
	//3，发送后台数据
	
	var messageJson = JSON.stringify({
		"name" : message
	});
	stompClient.send("/app/oneToOneTest/"+$("#destUsername").val(), {}, messageJson);
	//4，展示页面信息
	var str = "";
	str = '<div class="btalk"><span>' + myname + "说: " + text1
			+ '</span></div>';
	// window.location.href="http://localhost:8080/first/index.html";
	var Words = document.getElementById('words');
	Words.innerHTML = Words.innerHTML + str;

}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
	document.getElementById('message').innerHTML += innerHTML + '<br/>';
}